package org.spiderflow.core.executor.shape;

import org.spiderflow.common.context.SpiderContext;
import org.spiderflow.common.executor.ShapeExecutor;
import org.spiderflow.common.model.SpiderNode;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 等待执行结束执行器
 * @author zsh
 */
@Component
public class ForkJoinExecutor implements ShapeExecutor {

    /**
     * 缓存已完成节点的变量
     */
    private final Map<String, Map<String, Object>> cachedVariables = new HashMap<>();

    @Override
    public String supportShape() {
        return "forkJoin";
    }

    @Override
    public boolean allowExecuteNext(SpiderNode node, SpiderContext context, Map<String, Object> variables) {
        String key = context.getId() + "-" + node.getNodeId();
        boolean isDone = node.isDone();
        Map<String, Object> cached = cachedVariables.computeIfAbsent(key, k -> new HashMap<>(8));
        if (!isDone) {
            cached.putAll(variables);
        } else if (!cached.isEmpty()) {
            //将缓存的变量存入到当前变量中,传递给下一级
            variables.putAll(cached);
            cachedVariables.remove(key);
        }
        return isDone;
    }
}
